/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.application;

import java.io.File;
import java.util.Hashtable;
import java.util.concurrent.atomic.AtomicLong;


/**
 *
 * @author node1
 */
public class AutoIncrement {
    private static AutoIncrement instance;      
    private Hashtable table = null;
    
     public static AutoIncrement getInstance(){
        if (instance != null)
            return instance;
        instance = new AutoIncrement();
        return instance;
    }
     
     public AutoIncrement(){
         table = new Hashtable();
         File[] files = new File(ReadWriteFile.path).listFiles();
         int numberFile = files.length;
         for(int i = 0; i < numberFile; i++){
             if(files[i].isFile()){
                String fileName = files[i].getName();
                long value = ReadWriteFile.read(fileName);
                table.put(fileName, new AtomicLong(value));             
             }
         }
     }
     
    public long getAutoIncrement(String key){
        long result = -1;
        if(table.get(key) != null){
            AtomicLong curr = null;
            curr = (AtomicLong)table.get(key);
            result = curr.getAndIncrement();
            table.put(key, curr);
            ReadWriteFile.write(key, curr.get());
        }
        return result;
    }

    public long getNumberIncrement(String key){
        long result = -1;
        if(table.get(key) != null){
            AtomicLong curr = null;
            curr = (AtomicLong)table.get(key);
            result = curr.get();
            table.put(key, curr);
            ReadWriteFile.write(key, curr.get());
        }
        return result;
    }    
    
    public long setAutoIncrement(String key, long value){
        long result = -1;
        AtomicLong curr = new AtomicLong(value);
        if(table.get(key) != null){
            curr = (AtomicLong)table.get(key);
            result = curr.get();
        }
        table.put(key, curr);
        ReadWriteFile.write(key, curr.get());
        return result;        
    }

    public Hashtable getTable() {
        return table;
    }
}
